package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.BoardDAO;

import org.apache.log4j.Logger;

import vo.MemberVO;

/**
 * Servlet implementation class FrontController
 */
public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(FrontController.class);
	
	public ActionFactory factory = ActionFactory.getInstance();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FrontController() {
        super();
        // TODO Auto-generated constructor stub
    }

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			logger.info("new JDBC constructed.");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		doAction(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		doAction(request, response);
	}
	
	protected void doAction (HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		String servletPath = request.getServletPath();
		String command = servletPath.substring(servletPath.lastIndexOf("/") + 1);
		
		Action action = factory.getAction(command);
		
		logger.debug("command: " + command);
		logger.debug("action: " + action.toString());
		
		ActionForward af = action.execute(request, response);
		
		logger.debug(af);
		
		if(af.isRedirect()) {
			response.sendRedirect(af.getPath());
		} else {
			request.getRequestDispatcher(af.getPath()).forward(request, response);
		}
	}
}
